<template>
  <view class="appointment-container">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="search-input">
        <text class="iconfont icon-sousuo"></text>
        <input type="text" placeholder="搜索预约记录" v-model="searchText" @input="handleSearch"/>
      </view>
    </view>
    
    <!-- 内容区域 -->
    <view class="content-area">
      <!-- 预约状态标签 -->
      <view class="status-tabs">
        <view 
          class="tab-item" 
          :class="{ active: currentTab === 'all' }"
          @click="switchTab('all')"
        >全部</view>
        <view 
          class="tab-item" 
          :class="{ active: currentTab === 'unpaid' }"
          @click="switchTab('unpaid')"
        >待支付</view>
        <view 
          class="tab-item" 
          :class="{ active: currentTab === 'paid' }"
          @click="switchTab('paid')"
        >已支付</view>
      </view>
      
      <!-- 预约列表 -->
      <view class="appointment-list">
        <view class="appointment-item" v-for="item in filteredAppointments" :key="item.id">
          <view class="hospital-info">
            <text class="name">{{ item.hospitalName }}</text>
            <view class="status-group">
              <text class="status-tag payment" :class="item.paymentStatus">
                {{ getPaymentStatusText(item.paymentStatus) }}
              </text>
              <text class="status-tag" :class="item.status">
                {{ getStatusText(item.status) }}
              </text>
            </view>
          </view>
          
          <view class="detail-info">
            <text class="department">{{ item.departmentName }}</text>
            <text class="doctor">{{ item.doctorName }}</text>
          </view>
          
          <view class="time-info">
            <text class="date">就诊时间：{{ formatDate(item.appointmentDate) }}</text>
            <text class="time">{{ item.appointmentTime === 'morning' ? '上午' : '下午' }}</text>
          </view>
          
          <view class="action-buttons">
            <button 
              class="btn cancel-btn" 
              @click="cancelAppointment(item.id)"
            >
              <text class="iconfont icon-close"></text>
              取消预约
            </button>
            <button 
              class="btn pay-btn" 
              v-if="item.paymentStatus === 'unpaid'"
              @click="goToPay(item.id)"
            >
              <text class="iconfont icon-pay"></text>
              去支付
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getAppointmentList, deleteAppointment, payAppointment } from '@/api/appointment'

export default {
  data() {
    return {
      currentTab: 'all',
      appointments: [],
      searchText: '',
      userId: ''
    }
  },
  
  computed: {
    filteredAppointments() {
      let list = this.appointments
      
      // 根据tab筛选
      if (this.currentTab !== 'all') {
        list = list.filter(item => {
          switch (this.currentTab) {
            case 'unpaid':
              return item.paymentStatus === 'unpaid'
            case 'paid':
              return item.paymentStatus === 'paid'
            default:
              return true
          }
        })
      }
      
      // 根据搜索文本筛选
      if (this.searchText) {
        const searchLower = this.searchText.toLowerCase()
        list = list.filter(item => 
          item.hospitalName?.toLowerCase().includes(searchLower) ||
          item.doctorName?.toLowerCase().includes(searchLower) ||
          item.departmentName?.toLowerCase().includes(searchLower)
        )
      }
      
      // 按预约日期降序排序（最新的在前面）
      return list.sort((a, b) => 
        new Date(b.appointmentDate) - new Date(a.appointmentDate)
      )
    }
  },
  
  onShow() {
    this.userId = uni.getStorageSync('userId')
    if (!this.userId) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/login/index'
        })
      }, 1500)
      return
    }
    this.getAppointments()
  },
  
  methods: {
    // 获取预约列表
    async getAppointments() {
      try {
        const res = await getAppointmentList(this.userId)
        this.appointments = res
      } catch (error) {
        uni.showToast({
          title: error || '获取预约记录失败',
          icon: 'none'
        })
      }
    },
    
    // 删除预约记录
    async cancelAppointment(id) {
      try {
        const [err, res] = await uni.showModal({
          title: '提示',
          content: '确定要删除该预约记录吗？'
        })
        
        if (err || !res.confirm) return
        
        await deleteAppointment(id)
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
        
        // 刷新列表
        this.getAppointments()
        
      } catch (error) {
        uni.showToast({
          title: error || '删除失败',
          icon: 'none'
        })
      }
    },
    
    // 去支付
    goToPay(id) {
      console.log('正在跳转到支付页面，预约ID：', id)
      uni.navigateTo({
        url: `/pages/payment/index?appointmentId=${id}&userId=${this.userId}`,
        fail: (err) => {
          console.error('跳转失败：', err)
          uni.showToast({
            title: '跳转失败',
            icon: 'none'
          })
        }
      })
    },
    
    // 格式化日期
    formatDate(dateStr) {
      const date = new Date(dateStr)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()]
      return `${year}-${month}-${day} ${weekDay}`
    },
    
    // 获取支付状态文本
    getPaymentStatusText(status) {
      const statusMap = {
        unpaid: '待支付',
        paid: '已支付',
        refunded: '已退款'
      }
      return statusMap[status] || status
    },
    
    // 获取预约状态文本
    getStatusText(status) {
      const statusMap = {
        pending: '待确认',
        confirmed: '已确认',
        cancelled: '已取消'
      }
      return statusMap[status] || status
    },
    
    // 切换标签
    switchTab(tab) {
      this.currentTab = tab
    }
  }
}
</script>

<style lang="scss">
.appointment-container {
  height: calc(100vh - 44px - 50px);
  background: #f5f5f5;
  box-sizing: border-box;
  
  .search-bar {
    padding: 20rpx;
    background: #fff;
    
    .search-input {
      display: flex;
      align-items: center;
      background: #f5f5f5;
      border-radius: 32rpx;
      padding: 0 30rpx;
      height: 72rpx;
      
      .iconfont {
        font-size: 36rpx;
        color: #666;
        margin-right: 10rpx;
      }
      
      input {
        flex: 1;
        font-size: 28rpx;
      }
    }
  }
  
  .content-area {
    padding: 20rpx;
    
    .status-tabs {
      display: flex;
      background: #fff;
      padding: 20rpx;
      border-radius: 16rpx;
      margin-bottom: 20rpx;
      
      .tab-item {
        flex: 1;
        text-align: center;
        font-size: 28rpx;
        color: #666;
        padding: 10rpx 0;
        position: relative;
        
        &.active {
          color: #007AFF;
          font-weight: bold;
          
          &::after {
            content: '';
            position: absolute;
            bottom: -10rpx;
            left: 50%;
            transform: translateX(-50%);
            width: 40rpx;
            height: 4rpx;
            background: #007AFF;
            border-radius: 2rpx;
          }
        }
      }
    }
    
    .appointment-list {
      .appointment-item {
        background: #fff;
        border-radius: 20rpx;
        padding: 32rpx;
        margin-bottom: 24rpx;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
        transition: all 0.3s ease;
        
        &:active {
          transform: scale(0.995);
        }
        
        .hospital-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20rpx;
          
          .name {
            font-size: 34rpx;
            font-weight: 600;
            color: #333;
          }
          
          .status-group {
            display: flex;
            gap: 10rpx;
            
            .status-tag {
              font-size: 24rpx;
              padding: 6rpx 16rpx;
              border-radius: 6rpx;
              font-weight: 500;
              
              // 支付状态样式
              &.unpaid {
                background: #fff7e6;
                color: #fa8c16;
              }
              &.paid {
                background: #f6ffed;
                color: #52c41a;
              }
              &.refunded {
                background: #f5f5f5;
                color: #999;
              }
              
              // 预约状态样式
              &.pending {
                background: #e6f7ff;
                color: #1890ff;
              }
              &.confirmed {
                background: #f6ffed;
                color: #52c41a;
              }
              &.cancelled {
                background: #fff1f0;
                color: #f5222d;
              }
            }
          }
        }
        
        .detail-info {
          margin: 20rpx 0;
          
          .department, .doctor {
            font-size: 30rpx;
            color: #666;
          }
        }
        
        .time-info {
          color: #666;
          font-size: 28rpx;
          
          .time {
            color: #1890ff;
            font-weight: 500;
          }
        }
        
        .action-buttons {
          display: flex;
          justify-content: flex-end;
          align-items: center;
          gap: 20rpx;
          margin-top: 20rpx;
          
          .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 26rpx;
            transition: all 0.2s ease;
            
            &::after {
              border: none;
            }
            
            .iconfont {
              font-size: 28rpx;
              margin-right: 4rpx;
            }
            
            &.cancel-btn {
              background: transparent;
              color: #8c8c8c;
              padding: 12rpx 24rpx;
              border-radius: 30rpx;
              border: 1rpx solid #d9d9d9;
              
              &:active {
                background: #fafafa;
                border-color: #bfbfbf;
                color: #595959;
              }
            }
            
            &.pay-btn {
              background: linear-gradient(135deg, #1890ff, #096dd9);
              color: #fff;
              padding: 12rpx 32rpx;
              border-radius: 30rpx;
              box-shadow: 0 4rpx 12rpx rgba(24, 144, 255, 0.2);
              
              &:active {
                transform: translateY(2rpx);
                box-shadow: 0 2rpx 6rpx rgba(24, 144, 255, 0.2);
              }
            }
          }
        }
      }
    }
  }
}

.action-buttons {
  .btn {
    position: relative;
    z-index: 1;
  }
}
</style> 